﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Net;

namespace Trade.ExChangeSrv
{
    public class ExchangeSrv
    {
        public DataTable GetCurrencyExchangeList()
        {
            int iTrStart;
            int iTrEnd;

            int iTdStart;
            //int iTdEnd;

            byte[] bytePageData;

            DataTable dtCurrencyExchange = null;
            DataRow drCurrencyRow;

            WebClient webClient;


            string strPageHtml;
            string strCurrencyName_En;
            string strCurrencyName_Cn;
            string strPubTime;
            string strPubDate;

            decimal decBuyingRate;
            decimal decCashBuyingRate;
            decimal decSellingRate;
            decimal decMiddleRate;
            decimal decBocRate;


            webClient = new WebClient();
            try
            {
                bytePageData = webClient.DownloadData("http://www.boc.cn/sourcedb/whpj/index.html");
            }
            catch (Exception)
            {
                return null;
            }
            //bytePageData = webClient.DownloadData("http://www.boc.cn/en/common/service.jsp?category=ROOT%3Een%3EInformation+Center%3EMarket+Information%3EBOC+EXCHANGE+RATE+");
            strPageHtml = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytePageData).ToLower();
            MatchCollection matchs;
            // matchs = new Regex("<table width=\"810\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" bgcolor=\"#F2F2F2\" align=\"center\">((?:.|\n)*?)</table>", RegexOptions.IgnoreCase).Matches(strPageHtml);
            matchs = new Regex(" <table cellpadding=\"0\" align=\"left\" cellspacing=\"0\" width=\"100%\">((?:.|\n)*?)</table>", RegexOptions.IgnoreCase).Matches(strPageHtml);

            if (matchs.Count == 0)
            {
                Exception ex = new Exception("得到汇率出错！");
                throw (ex);
                return null;
            }
            strPageHtml = matchs[0].Groups[0].Value;
            if (strPageHtml.IndexOf("货币名称") > 0)
            {
                #region 创建存贮表
                dtCurrencyExchange = new DataTable("T_CurrenyExchange");
                dtCurrencyExchange.Columns.Add("CurrencyName", Type.GetType("System.String"));
                dtCurrencyExchange.Columns.Add("BuyingRate", Type.GetType("System.Decimal"));
                dtCurrencyExchange.Columns.Add("CashBuyingRate", Type.GetType("System.Decimal"));
                dtCurrencyExchange.Columns.Add("SellingRate", Type.GetType("System.Decimal"));
                dtCurrencyExchange.Columns.Add("MiddleRate", Type.GetType("System.Decimal"));
                dtCurrencyExchange.Columns.Add("BocRate", Type.GetType("System.Decimal"));
                dtCurrencyExchange.Columns.Add("PubDate", Type.GetType("System.String"));
                dtCurrencyExchange.Columns.Add("PubTime", Type.GetType("System.String"));
                #endregion
                iTrStart = strPageHtml.IndexOf("<tr>");
                iTrEnd = strPageHtml.IndexOf("</tr>", iTrStart);
                while (iTrStart > 0 && iTrEnd > 0 && iTrEnd > iTrStart)
                {
                    #region 初始数据
                    decBuyingRate = 0;
                    decCashBuyingRate = 0;
                    decSellingRate = 0;
                    decMiddleRate = 0;
                    decBocRate = 0;
                    strPubDate = "";
                    strPubTime = "";
                    strCurrencyName_Cn = "";
                    strCurrencyName_En = "";
                    #endregion
                    string strPageTemp = strPageHtml.Substring(iTrStart - 13, iTrEnd - iTrStart);
                    if (strPageTemp.IndexOf("<td") < 0 && strPageTemp.IndexOf("</td>") < 0)
                    {
                        strPageHtml = strPageHtml.Substring(iTrEnd);
                        continue;
                    }
                    iTdStart = strPageTemp.IndexOf("<td");
                    // strPageTemp = strPageTemp.Substring(iTdStart);
                    strPageTemp = strPageTemp.Replace("<td bgcolor=\"#ffffff\">", "").Replace("</tr>", "").Replace("\t", "").Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace(" ", "").Replace("<td>", "").Replace("<tr>", "");
                    strPageTemp = strPageTemp.Replace("</td>", "#");
                    string[] strSpli = strPageTemp.Split('#');
                    if (strSpli.Length < 8)
                        continue;
                    #region CurrencyName
                    strCurrencyName_Cn = strSpli[0];
                    if (strCurrencyName_Cn == string.Empty)
                        continue;
                    #endregion
                    #region BuyingRate
                    try
                    {
                        decBuyingRate = Convert.ToDecimal(strSpli[1]);
                    }
                    catch (Exception)
                    {
                        decBuyingRate = 0;
                    }
                    #endregion
                    #region CashBuyingRate
                    try
                    {
                        decCashBuyingRate = Convert.ToDecimal(strSpli[2]);
                    }
                    catch (Exception)
                    {
                        decCashBuyingRate = 0;
                    }
                    #endregion
                    #region SellingRate
                    try
                    {
                        decSellingRate = Convert.ToDecimal(strSpli[3]);
                    }
                    catch (Exception)
                    {
                        decSellingRate = 0;
                    }
                    #endregion
                    #region MiddleRate
                    try
                    {
                        decMiddleRate = Convert.ToDecimal(strSpli[4]);
                    }
                    catch (Exception)
                    {
                        decMiddleRate = 0;
                    }
                    #endregion

                    #region BocRate
                    try
                    {
                        decBocRate = Convert.ToDecimal(strSpli[5]);
                    }
                    catch (Exception)
                    {
                        decBocRate = 0;
                    }
                    #endregion

                    #region PubDate
                    strPubDate = strSpli[6];
                    #endregion

                    #region PubTime
                    strPubTime = strSpli[7];
                    #endregion

                    switch (strCurrencyName_Cn)
                    {
                        case "英镑":
                            strCurrencyName_En = "GBP";
                            break;
                        case "港币":
                            strCurrencyName_En = "HKD";
                            break;
                        case "美元":
                            strCurrencyName_En = "USD";
                            break;
                        case "瑞士法郎":
                            strCurrencyName_En = "CHF";
                            break;
                        case "新加坡元":
                            strCurrencyName_En = "SGD";
                            break;
                        case "瑞典克朗":
                            strCurrencyName_En = "SEK";
                            break;
                        case "丹麦克朗":
                            strCurrencyName_En = "DKK";
                            break;
                        case "挪威克朗":
                            strCurrencyName_En = "NOK";
                            break;
                        case "日元":
                            strCurrencyName_En = "JPY";
                            break;
                        case "加拿大元":
                            strCurrencyName_En = "CAD";
                            break;
                        case "澳大利亚元":
                            strCurrencyName_En = "AUD";
                            break;
                        case "欧元":
                            strCurrencyName_En = "EUR";
                            break;
                        case "澳门元":
                            strCurrencyName_En = "MOP";
                            break;
                        case "新西兰元":
                            strCurrencyName_En = "NZD";
                            break;
                        case "韩国元":
                            strCurrencyName_En = "KRW";
                            break;
                        case "泰国铢":
                            strCurrencyName_En = "THB";
                            break;
                        case "菲律宾比索":
                            strCurrencyName_En = "PHP";
                            break;
                    }
                    if (!string.IsNullOrEmpty(strCurrencyName_En))
                    {
                        drCurrencyRow = dtCurrencyExchange.NewRow();
                        drCurrencyRow["CurrencyName"] = strCurrencyName_En;
                        drCurrencyRow["BuyingRate"] = decBuyingRate;
                        drCurrencyRow["CashBuyingRate"] = decCashBuyingRate;
                        drCurrencyRow["SellingRate"] = decSellingRate;
                        drCurrencyRow["MiddleRate"] = decMiddleRate;
                        drCurrencyRow["BocRate"] = decBocRate;
                        drCurrencyRow["PubDate"] = strPubDate;
                        drCurrencyRow["PubTime"] = strPubTime;
                        dtCurrencyExchange.Rows.Add(drCurrencyRow);
                    }
                    //
                    strPageHtml = strPageHtml.Substring(iTrEnd);

                    iTrStart = strPageHtml.IndexOf("<tr");
                    if (iTrStart >= 0)
                    {
                        iTrEnd = strPageHtml.IndexOf("</tr>", iTrStart);
                    }
                }
                dtCurrencyExchange.AcceptChanges();
            }
            return dtCurrencyExchange;
        }
    }
}
